
import { generateId } from "@/utils/index";
import { getMetadata, getSourcesinkzh } from "@/api/project";
import { setFunctiondata } from "@/views/edge/projectionPage/js/index";
import { setTypeStores } from '@/views/edge/inputSourcePage/js/index'
import _ from 'lodash'
const state = {
  extensions: {},
  relateData: {}, //上下节点信息
  queryLists: {
    "WINDOW_FILTER_PROJECTION": {},
    "PATTERN": [],
    "SEQUENCE": [],
    "JOIN": []
  },
  metadata: [],//原始数据
  userAttributeList: [],
  succSin: {}
}
const mutations = {
  setStreamHandlerList: () => {

  },
  setHaving: (state, data) => {
    state.queryLists
      .WINDOW_FILTER_PROJECTION.having = data
  },
  setUserAttributeList: (state, data) => {
    state.userAttributeList = data
  },
  // 设置投射名称
  setQueryName: (state, data) => {
    state.queryLists
      .WINDOW_FILTER_PROJECTION.queryName = data
  },
  // 投射来源名称
  setQueryInput: (state, data) => {
    state.queryLists
      .WINDOW_FILTER_PROJECTION.queryInput.from = data
  },
  setMetadata: (state, data) => {
    // data.sort()
    state.metadata = data
  },

  setRelateData: (state, data) => {
    state.relateData = data
  },
  setSuccSin: (state, data) => {
    state.succSin = data
  },
  // 冬天修改left right的名字
  setLRname: (state, data) => {
    const { keyName, isLeftRight, val } = data
    let attrExt = state.extensions[keyName].find(item => item.name === '属性')?.list || []
    attrExt.forEach(item => {
      if (item.id == isLeftRight) {
        item.name = val
        item.value = val
        item.valueType = val
      }
      if (item.id == isLeftRight + '-attr') {
        // item.id = newVal
        const name = val + '.' + item.nameScpe
        item.name = name
        item.value = name
        item.valueType = name
      }
    })
    let attrExt2 = state.extensions['funArr'].find(item => item.name === '属性')
    let funArrFilter = state.extensions['funArrFilter'].find(item => item.name === '属性')
    attrExt2.list = attrExt.filter(item => item.id == 'right-attr' || item.id == 'left-attr')
    funArrFilter.list = attrExt.filter(item => item.id != 'right' && item.id != 'left')
  },
  // 插入left - right
  setAttrMetaData: (state, data) => {
    const { keyName, arr } = data
    let attrExt = state.extensions[keyName].find(item => item.name === '属性')
    let attrExtFilter = state.extensions['funArrFilter'].find(item => item.name === '属性')
    let attrExtArr = state.extensions['funArr'].find(item => item.name === '属性')
    if (attrExt && arr.length !== 0) {
      attrExt.list = attrExt.list.concat(arr)
      attrExtArr.list = attrExt.list.filter(item => item.id == 'right-attr' || item.id == 'left-attr')
      attrExtFilter.list = attrExt.list.filter(item => item.id != 'right' && item.id != 'left')
    }
  },
  setOperator: (state, data) => {
    let newData = _.cloneDeep(data)
    let Operator = state.extensions['Operator'][0].list
    Operator = Operator.filter(item => !item.isCondit)
    newData = newData.map(item => {
      return {
        id: item.id,
        name: item.conditionId,
        value: item.conditionId,
        valueType: item.conditionId,
        isCondit: true
      }
    })
    Operator = newData.concat(Operator)
    Operator = _.uniqBy(Operator, "id");
    state.extensions['Operator'][0].list = Operator
  },
  setUserInput: (state, data) => {
    let newData = _.cloneDeep(data)
    let attrArr = []
    newData.forEach(item => {
      if (item.attributeList) {
        item.attributeList.forEach(attr => {
          let name = ''
          if (item.conditionId) {
            name = `${item.conditionId}.${attr.name}`

          } else {
            name = `.${attr.name}`
          }
          attrArr.push({
            id: generateId(),
            name: name,
            value: name,
            valueType: name,
          })
        })
      } else {
        if (item.conditionId) {
          const name = `${item.conditionId}.`
          attrArr.push({
            id: generateId(),
            name: name,
            value: name,
            valueType: name,
          })
        }

      }

    })
    state.extensions['funArrAllNoAttr'][0].list = attrArr
    state.extensions['funArrAllNoAttrCondition'] = []
    let attributeList = attrArr.concat(state.relateData.targetCell.attributeList)
    state.extensions['funArrAllNoAttrCondition'] = _.cloneDeep(state.extensions['funArrAllNoAttr'])
    state.extensions['funArrAllNoAttrCondition'][0].list = _.cloneDeep(attributeList)
    console.log(state.extensions['funArrAllNoAttrCondition'])
  },
  // 最终的数据
  setExtensions: (state, data) => {
    const obj = _.cloneDeep(data)
    let extensionsObj = setFunctiondata(
      state.metadata,
      obj.relateData,
      obj.isName
    );
    state.extensions = extensionsObj
  }
}

const actions = {
  getMetadata({ commit }, sourceCell) {
    return new Promise(async (resolve, reject) => {
      const { data } = await getMetadata();
      // 数据整理(函数,过滤,窗口)
      let newSource = data.extensions.source.sources
      newSource.sort((a, b) => (a.name + '').localeCompare(b.name + ''))
      commit('setMetadata', data)
      resolve()
    });
  },
  getSuccSin({ commit }) {
    return new Promise(async (resolve, reject) => {
      if (localStorage.getItem('sourceSinkData')) {
        const sourceSinkData = JSON.parse(localStorage.getItem('sourceSinkData'))
        // const { data: sourceSinkData } = await getSourcesinkzh();
        const objKeys = Object.keys(sourceSinkData)
        for (let i = 0; i < objKeys.length; i++) {
          const item = objKeys[i];
          sourceSinkData[item].sort((a, b) => (a.name + "").localeCompare(b.name + ""));
        }
        console.log(sourceSinkData)
        let { sources, sinks, stores, sourceMap, sinkMap } = sourceSinkData;
        stores = setTypeStores(stores)
        commit('setSuccSin', { sources, sinks, stores, sourceMap, sinkMap })
        resolve()
      } else {
        // 如果不存在 从新登陆,从新保存
        this.dispatch('user/logout')
      }

    });
  },
}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  // getters
}
function useSort(data) {
  const newData = _.cloneDeep(data)
  newData.sort((a, b) => (a.name + "").localeCompare(b.name + ""));
  return newData
}